package com.hu.lock;

/**
 * @author 00355760
 * @功能：
 * @版本： V1
 * @版权： 信息技术有限公司（http://www.mychery.com/）
 * @作者： 磐石战队开发组  00355760
 * @日期： 2024/9/19 15:46
 */
public class Unsafe1 {
    public static void main(String[] args) {
        Account account =new Account(1000,"婚后共同财产");
        DrawingMoney man =new DrawingMoney(account,"男人",50);
        DrawingMoney woman =new DrawingMoney(account,"女人",100);
        man.start();
        woman.start();
    }
}
class Account {
    int money;
    String name;
    public Account(int money, String name) {
        this.money = money;
        this.name = name;
    }
}
class DrawingMoney extends Thread {
    final Account account;
    int drawingMoney;
    int nowMoney;
    public DrawingMoney(Account account, String name, int drawingMoney) {
        super(name);
        this.account = account;
        this.drawingMoney = drawingMoney;
    }

    @Override
    public void run() {
        //锁的是账户，变化的量，增删改
        // 1、建议使用共享资源作为锁对象，对于实例方法建议使用 this 作为锁对象
        // 2、对于静态方法建议使用字节码（【类名】.class）对象作为锁对象 Account.class
        synchronized (account)
        {if (account.money - drawingMoney < 0) {
            System.out.println(Thread.currentThread().getName() + "取钱失败，余额不足！");
            return;
        }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            account.money -= drawingMoney;
            nowMoney += drawingMoney;

            System.out.println(Thread.currentThread().getName() + "取出" + drawingMoney + "万元，手中余额为" + nowMoney);
            System.out.println(account.name + "余额为：" + account.money);
        }
    }
}
